import React, { PureComponent } from 'react';
import cx from 'classnames';
import S from './index.m.less';

export function getImgInfo(src = '') {
    const [, W = 100, H = W] = src.match(/-w([0-9]+)h([0-9]+)/i) || [];

    const MIN = 0.66;
    const MAX = 1.8;
    const height = Math.min(W * MAX, Math.max(H, W * MIN)); // 0.66 < 高/宽 < 1.8

    return {
        width: Number(W),
        height: Number(height),
    };
}

export default class extends PureComponent {
    static defaultProps = {
        list: [],
        renderItem: () => {},
        rowSpace: 1,
        columnSpace: 1,
        className: '',
    };

    handleList = (list = []) => {
        let leftHeight = 0;
        let rightHeight = 0;
        const leftList = [];
        const rightList = [];
        const { columnSpace } = this.props;
        list.forEach(item => {
            const height = this.props.getItemFinalHeight(item);

            if (leftHeight <= rightHeight) {
                leftHeight += height + columnSpace;
                leftList.push(item);
            } else {
                rightHeight += height + columnSpace;
                rightList.push(item);
            }
        });

        return {
            leftList,
            rightList,
        };
    };

    render() {
        const { leftList, rightList } = this.handleList(this.props.list);

        return (
            <div ref={this.refP} className={cx(S.wrap, 'waterFallWall', this.props.className)}>
                {this.props.list && this.props.list.length ? (
                    <>
                        <div style={{ marginRight: `${this.props.rowSpace}px` }}>
                            {leftList.map(this.props.renderItem)}
                        </div>
                        <div>{rightList.map(this.props.renderItem)}</div>
                    </>
                ) : null}
            </div>
        );
    }
}
